package com.ruipeng.shengyapo.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruipeng.shengyapo.locksocket.LockManager;
import com.ruipeng.shengyapo.locksocket.NettyChannelMap;
import com.ruipeng.shengyapo.model.BikeInfo;
import com.ruipeng.shengyapo.service.BikeService;
import com.ruipeng.shengyapo.service.LockService;
import com.ruipeng.shengyapo.utils.LatLonPoint;
import com.ruipeng.shengyapo.utils.LocationConverter;
import com.ruipeng.shengyapo.utils.ObjUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.SocketChannel;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

@Controller
@RequestMapping("/lock")
public class LockController {


    private static Logger log = Logger.getLogger("lock");
    
    @Autowired
	private LockService lockService;
    
    @Autowired
	private BikeService bikeService;

	@RequestMapping("testopen")
	@ResponseBody
	public String testopen(String imei) {
		SocketChannel sch = (SocketChannel) NettyChannelMap.get(imei);
		if (sch != null) {
            log.info("发送开锁指令: " + LockManager.getOpenLockCmd(imei));
			ByteBuf resp = Unpooled.copiedBuffer(LockManager.getOpenLockCmd(imei));
			sch.writeAndFlush(resp);
			return "ok";
		} else {
			return "no";
		}
	}
	
	@RequestMapping("open")
	@ResponseBody
	public String open(String imei) {
		System.out.println("LockIMEI: " + imei);
		SocketChannel sch = (SocketChannel) NettyChannelMap.get(imei);
		if (sch != null) {
            log.info("发送开锁指令: " + LockManager.getOmOpenLockCmd(imei));
			ByteBuf resp = Unpooled.copiedBuffer(LockManager.getOmOpenLockCmd(imei));
			sch.writeAndFlush(resp);
			return "ok";
		} else {
			return "no";
		}
	}
	
	@RequestMapping("card")
	@ResponseBody
	public String card(String imei) {
		SocketChannel sch = (SocketChannel) NettyChannelMap.get(imei);
		if (sch != null) {
            log.info("发送iccid指令: " + LockManager.getCardICCIDCmd(imei));
			ByteBuf resp = Unpooled.copiedBuffer(LockManager.getCardICCIDCmd(imei));
			sch.writeAndFlush(resp);
			return "ok";
		} else {
			return "no";
		}
	}
	
	@RequestMapping("close")
	@ResponseBody
	public String closedownLock(String imei) {
		SocketChannel sch = (SocketChannel) NettyChannelMap.get(imei);
		if (sch != null) {
            log.info("发送关机指令: " + LockManager.getClosedownLockCmd(imei));
			ByteBuf resp = Unpooled.copiedBuffer(LockManager.getClosedownLockCmd(imei));
			sch.writeAndFlush(resp);
			return "ok";
		} else {
			return "no";
		}
	}

	@RequestMapping("printLocks")
	@ResponseBody
	public String printLocks() {
		NettyChannelMap.print();
		return "";
	}

	@RequestMapping("closeLock")
	@ResponseBody
	public String closeLock(String imei) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("imei", imei);
		lockService.closeLock(params);
		return "";
	}

	@RequestMapping("getRecentOrderIsPush")
	@ResponseBody
	public String getRecentOrderIsPush(String imei) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("imei", imei);
		Map<String, Object> orderData = lockService.getRecentOrderByIMEI(params);
		if (orderData == null) {
			return "1"; // 未使用过的车没必要发通知
		}
		String push_app = "1";
		if (ObjUtils.isNotEmpty(orderData.get("push_app"))) {
			push_app = orderData.get("push_app").toString();
		}
		return push_app;
	}

	@RequestMapping("getRecentOrderIsSetEndPath")
	@ResponseBody
	public String getRecentOrderIsSetEndPath(String imei) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("imei", imei);
		Map<String, Object> orderData = lockService.getRecentOrderByIMEI(params);
		if (orderData == null) {
			return "1"; // 没有订单没必要修改是否设置终点
		}
		String set_endPath = orderData.get("set_endPath").toString();
		return set_endPath;
	}

	@RequestMapping("setEndPath")
	@ResponseBody
	public String setEndPath(String imei, String location) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("imei", imei);
		params.put("location", location);
		lockService.setRecentOrderEndPath(params);
		return "";
	}
	
	@RequestMapping("updateBikeLocation")
	@ResponseBody
	public String updateBikeLocation(String imei, String location) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("imei", imei);
		params.put("location", location);
		String[] locations = location.split(",");
		String cur_longitude = locations[0];
		String cur_latitude = locations[1];
		
		LatLonPoint point = LocationConverter.toGCJ02Point(Double.parseDouble(cur_latitude), Double.parseDouble(cur_longitude));
		
		params.put("cur_longitude", point.getLongitude() + "");
		params.put("cur_latitude", point.getLatitude() + "");
		
		lockService.updateBikeLocation(params);
		return "";
	}
	
	@RequestMapping("importLockInfoFromExcel")
	@ResponseBody
	public String importLockInfoFromExcel() {
		List<BikeInfo> bikeList = readExcel();
		if (!bikeList.isEmpty()) {
			
			bikeService.insertBikeInfoBatch(bikeList);
		}
		return "";
	}

	@RequestMapping("updateLockState")
    @ResponseBody
    public void updateBikeState(String imei,String lockState){
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("imei",imei);
        params.put("lockState",lockState);
        lockService.updateBikeState(params);
    }
	
	private List<BikeInfo> readExcel() {
		jxl.Workbook readwb = null;
		List<BikeInfo> bikeList = new ArrayList<BikeInfo>();
		try
		{
			// 构建Workbook对象, 只读Workbook对象
			// 直接从本地文件创建Workbook
			InputStream instream = new FileInputStream("/Users/pingping/Desktop/昇雅铂.xls");
			readwb = Workbook.getWorkbook(instream);

			// Sheet的下标是从0开始
			// 获取第一张Sheet表
			Sheet readsheet = readwb.getSheet(0);
			// 获取Sheet表中所包含的总列数
			int rsColumns = readsheet.getColumns();
			// 获取Sheet表中所包含的总行数
			int rsRows = readsheet.getRows();
			// 获取指定单元格的对象引用
			for (int i = 0; i < rsRows; i++)
			{
				BikeInfo bike = new BikeInfo();
				bike.setLockImei(readsheet.getCell(0, i).getContents());
				bike.setLockIccid(readsheet.getCell(1, i).getContents());
				bike.setBikeNo(readsheet.getCell(2, i).getContents());
				bikeList.add(bike);
				for (int j = 0; j < rsColumns; j++)
				{
					Cell cell = readsheet.getCell(j, i);
					System.out.print(cell.getContents() + " ");
				}
				System.out.println();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			readwb.close();
		}
		return bikeList;
	}
}
